package com.gitee.huanminabc.utils_tools.log_extend.log4j;

import com.gitee.huanminabc.jcommon.base.SnowIdUtil;
import com.gitee.huanminabc.jcommon.str.StringUtil;
import com.gitee.huanminabc.utils_tools.log_extend.LogTraceContextHolder;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.pattern.ConverterKeys;
import org.apache.logging.log4j.core.pattern.LogEventPatternConverter;

/**
 * @author 胡安民
 * 扩展对log4j2日志链路的追踪
 */
@Plugin(name = "logTraceConvert", category = "Converter")
@ConverterKeys({"traceId", "logTraceConvert"})
public class LogTraceConvert extends LogEventPatternConverter {

    private static final LogTraceConvert INSTANCE = new LogTraceConvert();

    public static LogTraceConvert newInstance(final String[] options) {
        return INSTANCE;
    }

    private LogTraceConvert() {
        super("traceId", "traceId");
    }

    protected LogTraceConvert(String name, String style) {
        super(name, style);
    }

    @Override
    public void format(LogEvent logEvent, StringBuilder stringBuilder) {
        String traceId = LogTraceContextHolder.get();
        if (StringUtil.isEmpty(traceId)){
            traceId = SnowIdUtil.uniqueLongHex();
        }
        stringBuilder.append(traceId);
    }
}